package cn.stylefeng.guns.sys.core.aop;

import cn.stylefeng.guns.sys.core.annotion.ApiToken;
import cn.stylefeng.guns.sys.core.util.AopGetParametersUtil;
import cn.stylefeng.guns.sys.core.util.TokenUtil;
import cn.stylefeng.guns.sys.modular.api.service.ApiAuthService;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;

/**
 * ApiToken检查的Aop
 * @author txl
 * @version 1.0
 * @date 2020/8/5 16:54
 * @description
 */
@Aspect
@Order(200)
public class ApiAop {
    @Resource
    private ApiAuthService apiAuthService;

    @Pointcut(value = "@annotation(cn.stylefeng.guns.sys.core.annotion.ApiToken)")
    private void cutPermission() {

    }

    @Around("cutPermission()")
    public Object doPermission(ProceedingJoinPoint point) throws Throwable {
        String token =null;
        String tokenUrl = null;
        String authToken = TokenUtil.getApiToken();
        if(ToolUtil.isEmpty(authToken)){
            MethodSignature signature = (MethodSignature) point.getSignature();
            // 获取方法上的指定注解
            ApiToken annotation = signature.getMethod().getAnnotation(ApiToken.class);
            // 获取注解中的参数
            tokenUrl = AopGetParametersUtil.getAnnotationValue(point, annotation.value());
            if(ToolUtil.isEmpty(tokenUrl)){
                return ResponseData.error("用户未登录");
            }else {
                token = tokenUrl;
            }
        }else {
            token = authToken;
        }
        if(ToolUtil.isEmpty(token)){
            return ResponseData.error("用户未登录");
        }
        ResponseData result = apiAuthService.verifyToken(token);
        if (ResponseData.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
            return point.proceed();
        }else {
            return ResponseData.error("用户未登录");
        }
    }
}